<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
	public $client = '';
	public $arrData = '';
	public $action = NULL;
	
	public function __construct() {
		parent::__construct();
		$this->output->set_header("Content-type: text/html; charset=utf-8");
		$this->load->model('Comm');
		$arrUserLogin = json_decode($this->Comm->getUserCookie(), true);
		$this->action = isset($this->uri->segments[2]) ? $this->uri->segments[2] : NULL;
		if(empty($arrUserLogin) && $this->action != 'uploadfile') {
			$this->load->helper('url');
			redirect('login.html?referer=' . $this->Comm->getReferUrl(), 'location', 302);
		}
		$this->arrData['user_login'] = $arrUserLogin;
		$this->client = 'web/';
		if($this->action != 'uploadfile') {
			$this->arrData['user_info'] = $this->Comm->getUserInfo($arrUserLogin['uid']);
		}
		$this->arrData['message'] = NULL;
		$this->arrData['siteinfo'] = $this->Comm->getTableCache('siteinfo', array('sid'=>1), true);
	}
	
	public function index() {
		$this->arrData['action'] = $this->action;
		$this->arrData['method'] = '';
		switch ($this->action) {
			case 'mydocs':
				$this->mydocs();
			break;
			case 'myincome':
				$this->myincome();
			break;
			case 'literature':
				$this->literature();
			break;
			case 'message':
				$this->message();
			break;
			case 'uploadfile':
				$this->uploadfile();
				return;
			break;
			case 'userimgmanager':
				$this->userimgmanager();
				return;
			break;
			case 'attribute' :
				$this->Comm->attribute();
				return;
			default:
				$action = 'home';
				$this->home();
			break; 
		}	
		$this->load->view($this->client . 'user_home', $this->arrData);
	}
	
	public function home() {
		$method = isset($this->uri->segments[3]) ? '_'.$this->uri->segments[3] : NULL;
		if(!empty($method)) {$function = 'home' . $method; $this->$function();}
		$this->arrData['method'] = $method;
		$this->arrData['__META'] = $this->Comm->getMeta($this->arrData['user_info']['nick_name'] . '的首页');
		$this->arrData['nav'] = "home";
	}
	public function home_myportrait() {
		$uid = $this->arrData['user_login']['uid'];
		$upload_ext = $this->Comm->encrypt($uid) . '&token=' . $this->Comm->getToken($uid, date("H"));
		$ulpoad_url = $this->config->base_url('user/uploadfile?uploadtype=my_pic&uploadid='.$upload_ext);
		$this->arrData['ulpoad_url'] = $ulpoad_url;
	}
	public function home_myinfo() {
		$this->arrData['__META'] = $this->Comm->getMeta('我的资料');
		$this->arrData['nav'] = "home";
	}
	public function literature() {
		$method = isset($this->uri->segments[3]) ? '_'.$this->uri->segments[3] : NULL;
		if(!empty($method)) {$function = 'literature' . $method; $this->$function();}
		$this->arrData['nav'] = "literature";
		$this->arrData['method'] = $method;
		$this->arrData['channel'] = $this->Comm->getChannel();
		$this->arrData['__META'] = $this->Comm->getMeta('我的创作');
	}
	public function myincome() {
		$method = isset($this->uri->segments[3]) ? '_'.$this->uri->segments[3] : NULL;
		if(!empty($method)) {$function = 'myincome' . $method; $this->$function();}
		$this->arrData['nav'] = "myincome";
		$this->arrData['method'] = $method;
		$this->arrData['channel'] = $this->Comm->getChannel();
		$this->arrData['__META'] = $this->Comm->getMeta('我的消费明细');
	}
	public function myincome_details() {
		$arrPageList = $this->Comm->getListPage('pay_reading', array('uid'=>$this->arrData['user_login']['uid']), 
		                                        'prid, rid, own_uid, price, coin, pay_date', array('orderBy'=>'prid desc'));
		$strRid = $strUid = '';
		$num = count($arrPageList['list']);
		for($i = 0; $i < $num; $i++) {
			$strRid .= $arrPageList['list'][$i]['rid'] . ',';
			$strUid .= $arrPageList['list'][$i]['own_uid'] . ',';
		}
		$strRid = trim($strRid, ',');
		$strUid = trim($strUid, ',');
		$titleReading = NULL;
		if(!empty($strRid)) {
			$arrReading =  $this->Comm->getList('reading', 'title, rid', "rid IN($strRid)");
			$titleReading = $this->Comm->tableHash('rid', $arrReading);
		}
		if(!empty($strUid)) {
			$arrUser =  $this->Comm->getList('user_info', 'nick_name,uid', "uid IN($strUid)");
			$nameUser = $this->Comm->tableHash('uid', $arrUser);
		}
		$this->arrData['pay_reading'] = $arrPageList['list'];
		$this->arrData['titleReading'] = $titleReading;
		$this->arrData['nameUser'] = $nameUser;
	}
	public function myincome_money() {
	}
	public function message() {
		$method = isset($this->uri->segments[3]) ? '_'.$this->uri->segments[3] : NULL;
		if(!empty($method)) {$function = 'message' . $method; $this->$function();}
		$this->arrData['nav'] = "message";
		$this->arrData['method'] = $method;
		$this->arrData['channel'] = $this->Comm->getChannel();
		$this->arrData['__META'] = $this->Comm->getMeta('我的消息中心');
	}
	public function mydocs() {
		$method = isset($this->uri->segments[3]) ? '_'.$this->uri->segments[3] : NULL;
		if(!empty($method)) {$function = 'mydocs' . $method; $this->$function();} else {
			$arrPageList = $this->Comm->getListPage('reading', array('uid'=>$this->arrData['user_login']['uid']), 
		                                        'rid, cid, title, pic, pic_host, price, use_coin_pay, coin_price, add_date', array('orderBy'=>'add_date desc'));
			$this->arrData['arrPageList'] = $arrPageList;
		}
		$this->load->helper('form');
		$this->arrData['nav'] = "mydocs";
		$this->arrData['method'] = $method;
		$this->arrData['channel'] = $this->Comm->getChannel();
		$this->arrData['__META'] = $this->Comm->getMeta('我的文档');
	}
	public function mydocs_myfaver() {
		$arrPageList = $this->Comm->getListPage('user_reading_faver', array('uid'=>$this->arrData['user_login']['uid']), 
		                                        'own_uid, rid, add_date', array('orderBy'=>'add_date desc'));
		$num = count($arrPageList['list']);
		$strRid = $strUid = $arrReading = NULL;
		for($i = 0; $i < $num; $i++) {
			$strRid .= $arrPageList['list'][$i]['rid'] . ',';
		}
		$strRid = trim($strRid, ',');
		if(!empty($strRid)) {
			$arrReading =  $this->Comm->getList('reading', 'rid, cid, title, desc, pic, pic_host', "rid IN($strRid)");
			$this->arrData['addDate'] = $this->Comm->tableHash('rid', $arrPageList['list']);
		}
		$this->arrData['reading'] = $arrReading;
	}
	public function mydocs_uploadlist() {
		$this->arrData['docs'] = $this->Comm->getList('reading_temporary', 'rtid, title, file_title, read_host, file_path,pic, pic_host, doc_type, price, add_date, auditing', 
													   array('uid'=>$this->arrData['user_login']['uid']), NULL,
													   array('orderBy'=>'rtid desc'));
	}
	public function mydocs_edit() {
		$__H = $this->input->post('__H');
		$rtid = $this->input->get('rtid');
		$this->arrData['next_rtid'] = $this->input->get('next_rtid');
		$arrEditRead = '';
		$uid = $this->arrData['user_login']['uid'];
		/*$arrExtend['orderBy'] = 'cid asc, father_id asc, orders asc, aid asc';
		$this->arrData['attribute'] = $this->Comm->getTableCache('attribute', NULL, false, NULL, $arrExtend);
		$this->arrData['attribute_title'] = $this->Comm->tableHash('aid', $this->arrData['attribute']);*/
		if($rtid > 0) { 
			$arrEditRead = $this->Comm->getList('reading_temporary', 'rtid, cid, title, file_title, 
			               synopsis, desc, read_host, file_path, pic, pic_host, doc_type, price, add_date, auditing',
			               "uid = '$uid' and rtid in('$rtid')", array(0,5));
			$this->arrData['edit_read_attr'] = $this->Comm->getList('reading_tmp_attribute', '*', array('rtid'=>$rtid));
			$edit_read_property = $this->Comm->getList('reading_tmp_property', '*', array('rtid'=>$rtid));
			$this->arrData['edit_read_property'] =$this->Comm->tableHash('pid', $edit_read_property);
			$arrAttribute = $this->Comm->attribute($arrEditRead[0]['cid'], true);
			$this->arrData['attribute'] = $arrAttribute['attribute'];
			$this->arrData['attribute_title'] = $this->Comm->tableHash('aid', $this->arrData['attribute']);
			$this->arrData['property'] = $arrAttribute['property'];
		}
		if($__H == 'update') {
			$arrPost = $this->input->post();
			$next_rtid = $arrPost['next_rtid'];
			if(!empty($arrPost) && isset($arrPost['editid'][0])) {
				$arrAttribute = $this->Comm->attribute($arrPost['channel'][0], true);
				$this->arrData['attribute_title'] = $this->Comm->tableHash('aid', $arrAttribute['attribute']);
				foreach($arrPost['editid'] as $k => $v) {
					if($v > 0 && !empty($arrPost['title'][$k]) && $arrPost['channel'][$k] > 0) {
						$arrData['title'] = $arrPost['title'][$k];
						$arrData['synopsis'] = $arrPost['synopsis'][$k];
						$arrData['pic'] = $arrPost['pic'][$k];
						if(!empty($arrData['pic'])) {
							preg_match("/[0-9]{4}\/[0-9]{2}\-[0-9]{2}\//", $arrData['pic'], $arrMatch);
							if(isset($arrMatch[0])) {
								$path = $arrMatch[0];
								$arrMatch = explode($path, $arrData['pic']);
								$arrData['pic'] = $path . $arrMatch[1];
								$arrData['pic_host'] = $arrMatch[0];
							}	
						}
						$arrData['cid'] = $arrPost['channel'][$k];
						$arrData['desc'] = $arrPost['desc'][$k];
						$arrData['auditing'] = '1';
						if($arrPost['price'][$k] > 0) $arrData['price'] = $arrPost['price'][$k];
						$editid = $v;
					
						$this->Comm->delete('reading_tmp_attribute', array('rtid'=>$editid));
						$i = 0;
						$filterI = 0;
						$replaceSql = '';
						if(isset($arrPost['attribute'][$k])) {
							$arrAttr = $arrPost['attribute'][$k];
							foreach($arrAttr as $kk => $vv) {
								$vv = trim($vv);
								$arrAttrData[$i]['rtid'] = $editid;
								$arrAttrData[$i]['cid'] = $arrData['cid'];
								$arrAttrData[$i]['aid'] = $kk;
								$arrAttrData[$i]['values'] = $vv;
								if($this->arrData['attribute_title'][$kk]['is_filter'] == 1) {
									if(!empty($vv)) $replaceSql .= "('$kk','$vv', '$editid', '".$arrData['cid']."'),";
									$arrData['attr' . ($filterI + 1)] = $kk;
									$arrData['value' . ($filterI + 1)] = $vv;
									$filterI++;
								}
								$i++;
							}
							$this->Comm->insert('reading_tmp_attribute', $arrAttrData, true);
						}
						//执行更新操作
						$this->Comm->update('reading_temporary', $arrData, array('uid'=>$uid, 'rtid'=>$editid));
						//
						$replaceSql = trim($replaceSql, ',');
						if(!empty($replaceSql)) {
							$this->Comm->delete('reading_tmp_filter', array('rtid'=>$editid));
							$this->Comm->query('insert ignore into reading_tmp_filter(aid, `values`, rtid, cid) values '.$replaceSql);		
						}
						//
						$this->Comm->delete('reading_tmp_property', array('rtid'=>$editid));
						if(isset($arrPost['property'][$k])) {
							$arrProperty = $arrPost['property'][$k];
							$i = 0;
							$replaceSql = '';
							foreach($arrProperty as $kk => $vv) {
								$arrPropertyData[$i]['rtid'] = $editid;
								$arrPropertyData[$i]['cid'] = $arrData['cid'];
								$arrPropertyData[$i]['pid'] = $kk;
								$i++;
							}
							$this->Comm->insert('reading_tmp_property', $arrPropertyData, true);
						}
					}
				}
				$this->arrData['message_edit_url'] = $this->config->base_url('user/mydocs/edit?rtid='.$editid);
				$this->arrData['message_edit_next_url'] = '';
				if($next_rtid > 0) $this->arrData['message_edit_next_url'] = $this->config->base_url('user/mydocs/edit?rtid='.$next_rtid);
				$this->arrData['message'] = "更新信息成功，返回";
			}
			
		}
		$this->arrData['edit_read'] = $arrEditRead;
		$upload_ext = $this->Comm->encrypt($uid) . '&token=' . $this->Comm->getToken($this->arrData['user_login']['uid'], date("H"));
		$ulpoad_url = $this->config->base_url('user/uploadfile?uploadtype=pic&uploadid='.$upload_ext);
		$this->arrData['ulpoad_url'] = $ulpoad_url;
	}
	public function mydocs_upload() {
		$arrHosts = $this->Comm->getTableCache('hosts_ip');
		$arrNetwork = NULL;
		$upload_ext = $this->Comm->encrypt($this->arrData['user_login']['uid']) . '&token=' . $this->Comm->getToken($this->arrData['user_login']['uid'], date("H"));
		$ulpoad_url = $this->config->base_url('user/uploadfile?uploadid='.$upload_ext);
		if(!empty($arrHosts)) {
			foreach($arrHosts as $k => $v) {
				$v['network_url'] = trim($v['network_url']);
				if(!empty($v['network_url'])) {
					$arrNetwork[] = $v['network_url'];
				}
			}
		}
		$num = count($arrNetwork);
		if($num == 1) $ulpoad_url = $arrNetwork[0];
		if($num > 1) $ulpoad_url = $arrNetwork[rand(0, $num - 1)];
		$this->arrData['ulpoad_url'] = $ulpoad_url;
	}
	
	public function uploadfile() {
		$uploadid = $this->input->get('uploadid');
		$token = $this->input->get('token');
		$uploadtype = $this->input->get('uploadtype');
		$uid = $this->Comm->decrypt($uploadid);
		$this->load->library('upload');
		$arrHosts = $this->Comm->getTableCache('hosts_ip');
		if($uploadtype == 'pic' || $uploadtype == 'my_pic') {
			if(empty($uid)) {
				echo json_encode(array('error' => 1, 'message' => '登录超时，请重新登录！'));
				return;	
			}
			$arrPicHost = $arrResize = NULL;
			foreach($arrHosts as $k => $v) {
				if($v['types'] == 'pic_host' && $v['is_use'] == 1) {
					$arrPicHost[] = $v;
				}
			}
			if(empty($arrPicHost)) {
				echo json_encode(array('error' => 1, 'message' => '没有设置文件主机,请设置.'));
				return;	
			}
			$arrPicHost = $arrPicHost[rand(0, count($arrPicHost) - 1)];
			$fileid = date("YmdHis") . trim(substr(microtime(), 2, 6));//GMT+8
			$targetDir = $this->Comm->createDataDir($arrPicHost['local_path']);
			$save_path = $this->config->item('filedir').$arrPicHost['local_path'].$targetDir;
			if($uploadtype == 'my_pic') {
				$arrResize['width'] = 50; $arrResize['height'] = 50;
				//$targetDir = $this->Comm->createUserDir($uid);
				//$save_path = $this->config->item('filedir').$arrPicHost['local_path'].$targetDir;
				$fileid = 'my_pic';
			}
			$jsonResult = $this->upload->uploadPic($save_path, $fileid, $arrPicHost['host_name'] . $targetDir, $arrResize);
			$arrJsonResult = json_decode($jsonResult, true);
			if($uploadtype == 'pic') {
				$arrData['uid'] = $uid;
				$arrData['pic_host'] = $arrPicHost['host_name'];
				$arrData['pic_path'] = $targetDir . $arrJsonResult['filename'];
				$arrData['size'] = $arrJsonResult['size'];
				$arrData['pic_title'] = $arrJsonResult['pic_title'];
				$arrData['pic_type'] = $arrJsonResult['pic_type'];
				$this->Comm->insert('user_pic', $arrData);
			}
			if($uploadtype == 'my_pic') {
				$this->Comm->update('user_info', array('my_pic'=>$arrPicHost['host_name'] . $targetDir . $arrJsonResult['filename']), array('uid'=>$uid));
			}
			header('Content-type: application/json; charset=UTF-8');
			echo $jsonResult;
			return;	
		}
		
		if(empty($uid)) {
			echo ('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "login error, 请重新登录."}, "id" : "id"}');
			return;	
		}
		if($this->Comm->getToken($uid, date("H")) != $token) {
			echo ('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "time out, 请刷新页面."}, "id" : "id"}');
			return;	
		}
		$arrReadHost = NULL;
		foreach($arrHosts as $k => $v) {
			if($v['types'] == 'read_host' && $v['is_use'] == 1) {
				$arrReadHost[] = $v;
			}
		}
		if(empty($arrReadHost)) {
			echo ('{"jsonrpc" : "2.0", "error" : {"code": 106, "message": "no file host, 没有设置文件主机,请设置."}, "id" : "id"}');
			return;	
		}
		$arrReadHost = $arrReadHost[rand(0, count($arrReadHost) - 1)];
		$targetDir = $this->Comm->createDataDir($arrReadHost['local_path']);
		$targetdfile = date("YmdHis") . trim(substr(microtime(), 2, 6));//GMT+8
		$targetdfile = md5(md5($this->input->post('name')).$uid);
		$jsonResult = $this->upload->upload($this->config->item('filedir').$arrReadHost['local_path'].$targetDir, $targetdfile);
		$arrJsonResult = json_decode($jsonResult, true);
		if(isset($arrJsonResult['result']) && $arrJsonResult['result'] == 'success') {
			$arrData['uid'] = $uid;
			$arrData['file_title'] = $arrData['title'] = $arrJsonResult['srcName'];
			$arrData['doc_type'] = $arrJsonResult['fileExt'];
			$arrData['read_host'] = $arrReadHost['host_name'];
			$arrData['file_path'] = $targetDir . $arrJsonResult['fileName'];
			$this->Comm->insert('reading_temporary', $arrData);
			$rtid = $this->Comm->getInsertId();
			$arrJsonResult['rtid'] = $rtid;
		}
		echo json_encode($arrJsonResult);
	}
	
	public function userimgmanager() {
		if($this->input->get('types')== 'my_pic') {
			$arrPic = $this->Comm->getList('user_info', 'my_pic pic_path', 
		                                array('uid'=>$this->arrData['user_login']['uid']));
			if(!empty($arrPic[0]['pic_path'])) {$arrPic[0]['size'] = $arrPic[0]['pic_host'] = $arrPic[0]['add_date'] = '';} else {
				$arrPic = NULL;
			}
		} else {
			$arrPic = $this->Comm->getList('user_pic', 'pid, rid, uid, pic_title, pic_host, pic_path, size, add_date', 
		                                array('uid'=>$this->arrData['user_login']['uid']));
		}
		$arrJsonPic = NULL;
		if(!empty($arrPic)) {
			$arrJsonPic["moveup_dir_path"] = '';
			$arrJsonPic["current_dir_path"] = '';
			$arrJsonPic["current_url"] = '';//$arrPic[0]['pic_host'];
			$arrJsonPic["total_count"] = count($arrPic);
			foreach($arrPic as $k => $v) {
				$arrJsonPic['file_list'][$k]["is_dir"] = false;
				$arrJsonPic['file_list'][$k]["has_file"] = false;
				$arrJsonPic['file_list'][$k]["filesize"] = $v['size'];
				$arrJsonPic['file_list'][$k]["dir_path"] = '';
				$arrJsonPic['file_list'][$k]["is_photo"] = true;
				$arrJsonPic['file_list'][$k]["filetype"] = 'jpg';
				$arrJsonPic['file_list'][$k]["filename"] = $v['pic_host'].$v['pic_path'];
				$arrJsonPic['file_list'][$k]["datetime"] = $v['add_date'];
			}
		}
		echo json_encode($arrJsonPic);
		//echo '{"moveup_dir_path":"","current_dir_path":"","current_url":"http:\/\/www.pupt.com\/ke4\/php\/..\/attached\/","total_count":5,"file_list":[{"is_dir":false,"has_file":false,"filesize":208736,"dir_path":"","is_photo":true,"filetype":"jpg","filename":"1241601537255682809.jpg","datetime":"2011-08-02 15:32:43"},{"is_dir":false,"has_file":false,"filesize":14966,"dir_path":"","is_photo":true,"filetype":"jpg","filename":"1_192040_1.jpg","datetime":"2011-08-02 15:32:45"},{"is_dir":false,"has_file":false,"filesize":245132,"dir_path":"","is_photo":true,"filetype":"jpg","filename":"2009321101428.jpg","datetime":"2011-08-02 15:32:45"},{"is_dir":false,"has_file":false,"filesize":229316,"dir_path":"","is_photo":true,"filetype":"jpg","filename":"24000750690483.jpg","datetime":"2011-08-02 15:32:50"},{"is_dir":false,"has_file":false,"filesize":26094,"dir_path":"","is_photo":true,"filetype":"jpg","filename":"W020091124524510014093.jpg","datetime":"2011-08-02 15:32:47"}]}';	
	}
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */